package wfw.cn.ktcmanager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import wfw.cn.ktc_common.unit.JwtUtil;

import javax.servlet.http.HttpServletRequest;

@Component
public class ZFilter extends ZuulFilter {

    @Autowired
    private Environment environment;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String auth = request.getHeader("auth");
        String prefix = environment.getProperty("jwt.config.prefix");
        context.getResponse().setContentType("text/html;charset=utf-8");
        if (auth==null ||!auth.startsWith(prefix)){
            context.setSendZuulResponse(false);
            context.setResponseBody("请登录");
        }
        String token = auth.substring(prefix.length());
        Claims claims = jwtUtil.parseJWT(token);
        if (!claims.get("role").toString().equals("user")){
            context.setSendZuulResponse(false);
            context.setResponseBody("权限不足");
        }
        return null;
    }
}
